package com.matrix.draft.sockettest.day9;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

public class MultiProtoClient {

    private String TARGET_HOST = "127.0.0.1";

    private Integer TARGET_PORT = 8080;

    public MultiProtoClient() {

    }

    public MultiProtoClient(String TARGET_HOST, Integer TARGET_PORT) {
        this.TARGET_HOST = TARGET_HOST;
        this.TARGET_PORT = TARGET_PORT;
    }

    public void run() {
        EventLoopGroup eventLoopGroup = null;
        try {
            eventLoopGroup = new NioEventLoopGroup();
            Channel ch = new Bootstrap()
                    .group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) {
                            // In Bound Handlers
                            ch.pipeline().addLast("protoEncoder",new ProtobufEncoder());
                            ch.pipeline().addLast("protoClientHandler", new MultiProtoClientHandler());
                            // Out Bound Handlers
                        }
                    })
                    .connect(TARGET_HOST, TARGET_PORT)
                    .sync()
                    .channel();
            System.out.println("---------------"+ch.localAddress()+"-------------------");
            ch.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new MultiProtoClient("127.0.0.1", 8080).run();
    }
}
